package com.eol.common.context;



import com.eol.common.constants.BaseCommonConstants;
import com.eol.common.jwt.TokenData;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: liulinhui
 * Date: 2018-11-26
 * Time: 19:46
 * Description:  BaseContextHandler
 */
public class BaseContextHandler {
    private static final ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

    public static void set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        map.put(key, value);
    }

    public static Object get(String key) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        return map.get(key);
    }

    public static void setTokenData(TokenData tokenData) {
        set(BaseCommonConstants.TOKEN_DATA, tokenData);
    }

    public static TokenData getTokenData() {
        return get(BaseCommonConstants.TOKEN_DATA) == null ? null : (TokenData) get(BaseCommonConstants.TOKEN_DATA);
    }

    public static void setAccessToken(String token) {
        set(BaseCommonConstants.ACCESS_TOKEN, token);
    }

    public static String getAccessToken() {
        return getObjectValue(get(BaseCommonConstants.ACCESS_TOKEN));
    }

    private static String getObjectValue(Object obj) {
        return obj == null ? "" : obj.toString();
    }

    /**
     * 清空 threadLocal
     */
    public static void remove() {
        threadLocal.remove();
    }
}
